 
package com.ng.sys.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.ng.common.redis.lock.annotation.RedisLock;
import com.ng.common.utils.DesUtils;
import com.ng.common.utils.MD5Utils;
import com.ng.common.utils.R;
import com.ng.sys.entity.SysUserEntity;
import com.ng.sys.form.SysLoginForm;
import com.ng.sys.service.SysCaptchaService;
import com.ng.sys.service.SysUserService;
import com.ng.sys.service.SysUserTokenService;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

/**
 * 认证模块
 *
 * @author Chill
 */
@RestController
@RequestMapping("/auth")
@Api(value = "用户授权认证", tags = "授权接口")
@Slf4j
public class AuthController {

	@Autowired
	private SysCaptchaService sysCaptchaService;
	
	@Autowired
	private SysUserService sysUserService ;
	
	@Autowired
	private SysUserTokenService sysUserTokenService;
	 
	
	/**
	 * 验证码
	 */
	@GetMapping("/captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		
		log.info("captcha , uuid:[{}]" , uuid );

		//获取图片验证码
		BufferedImage image = sysCaptchaService.nextCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		out.flush();
		out.close();
	}

	
	/**
	 * 验证码
	 */
	@GetMapping("/captchaBase64")
	public R<String> captchaBase64(String uuid)throws ServletException, IOException {
		 

		//获取图片验证码
		BufferedImage image = sysCaptchaService.nextCaptcha(uuid);
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", out);
		out.flush();
		out.close();
		
		byte[] data = out.toByteArray();
		
		String base64 = Base64.getEncoder().encodeToString(data).trim();
  
		base64 = "data:image/jpg;base64," + base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
         
		 
		return R.ok(String.class).setData(base64);
	}
	
	/**
	 * 登录
	 */
	@PostMapping("/account")
	public R<Object> login(@RequestBody  SysLoginForm form)throws IOException {
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return R.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserNo(form.getUserNo());
		if(user == null ) {
			return R.error("账号或密码不正确");
		}
		
	 
		String dePass = DesUtils.desEncrypt(form.getPassword());
		
		//密码还原
//		String dePass = RsaUtils.decryptByPrivateKey(form.getPassword());
		if(dePass == null) {
			return R.error("密码不正确");
		}
		
		//账号不存在、密码错误
		String pass = MD5Utils.md5Pass(dePass.trim(),  user.getSalt());
		if(StringUtils.isBlank(user.getPassword()) || !user.getPassword().equals(pass)) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}
 
		
		//生成token，并保存到数据库
		String token =  sysUserTokenService.createToken(user.getUserId());
		
		// 更新用户最后登录时间
		
		Date curr = new Date();
		SysUserEntity update = new SysUserEntity();
		update.setLastLoginTime(curr);
		update.setUserId(user.getUserId());
		
		sysUserService.updateById(update);
		
		
		 
		SysUserEntity copyUser = new SysUserEntity();
		
		// 用户复制,然后密码置为空
		org.springframework.beans.BeanUtils.copyProperties(user, copyUser);
		
		copyUser.setPassword(null);
		
		JSONObject jo = new JSONObject();
		jo.put("token", token);
		jo.put("user", copyUser);
		
		return R.ok().setData(jo);
	}
 
	 
	@RedisLock(key = "#id" )
	@GetMapping("/testLock")
	public R<Object> testLock(String id)  {
		System.out.println("我进来了111");
		try {
			Thread.sleep(10 * 1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("我结束了111");
		return R.ok().setData("success");
	}

}
